# IR Beacon RGB565 Tracking Example
#
# This example shows off IR beacon RGB565 tracking using the OpenMV Cam.

import sensor, image, math,time,screen

thresholds = [(100, 100, 0, 0, 0, 0)] # thresholds for bright white light from IR.

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
clock = time.clock()

screen.init(40)
img_colorful=sensor.alloc_extra_fb(320,240,sensor.RGB565)   #声明一个彩色画布，用于屏幕显示

ROI=(140,100,20,20)

while(True):
    clock.tick()
    img = sensor.snapshot()
    statistics=img.get_statistics(roi=ROI)
    color_l=statistics.l_mode()
    color_a=statistics.a_mode()
    color_b=statistics.b_mode()
    #print(statistics)
    #img.draw_rectangle(ROI)
    Lmin = color_l - 30
    Lmax = color_l + 30
    Amin = color_a - 30
    Amax = color_a + 30
    Bmin = color_b - 30
    Bmax = color_b + 30
    if screen.press:    #如果触屏被按下
        #通过x、y坐标画点
        img.draw_circle(screen.x , screen.y , 3,color=(255,0,0),fill=True)
        img.draw_circle(screen.x , screen.y , 15,color=(255,0,0))
        thresholds =  [(Lmin,Lmax,Amin,Amax,Bmin,Bmax)]
    blobs = img.find_blobs(thresholds,\
            x_stride=5,y_stride=5,pixels_threshold=50)
    if blobs:
        blob = max(blobs, key = lambda b: b.pixels())
        blob = max(blobs, key = lambda b: b.area())
        if blob.w()>2 and blob.h()>2:
            img.draw_cross(blob.cx(),blob.cy(),color=(0,255,0))
            img.draw_rectangle(blob.rect())
    img_colorful.draw_image(img,0,0)
    img_colorful.draw_string(0,0,str(round(clock.fps(),2)))
    screen.display(img_colorful)
